package kr.ac.kaist.vrowser.controllers;

import java.sql.SQLException;
import java.util.List;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;

import kr.ac.kaist.vrowser.application.VrowserApplication;
import kr.ac.kaist.vrowser.db.models.Form;

public class FormController extends BaseController {

	private Dao<Form, Integer> formDao;
	
	public FormController(VrowserApplication app) {
		super(app);
		
		formDao = app.getDatabaseHelper().getFormDao();
	}
	
	public void addOrEditForm(String name, String value, String url) throws SQLException{
		Form f = new Form();
		f.name = name;
		f.value = value;
		f.url = url;
		
		Form _f = findForm(name, url);
		if (_f != null){
			f.id = _f.id;
		}
		
		formDao.createOrUpdate(f);
	}
	
	public String getForm(String name, String url) throws SQLException{
		Form f= findForm(name, url);
		String value = "";
		if(f!= null){
			value = f.value;
		}
		
		if (value == null){
			return "";
		}
		
		return value;
	}
	
	
	private Form findForm(String name, String url) throws SQLException{
		PreparedQuery<Form> query = formDao.queryBuilder().where().eq("name", name).and().eq("url", url).prepare();
		List<Form> result = formDao.query(query);
		
		if (result.size() > 0){
			return result.get(0);
		}
		
		return null;
		
	}

}
